// pages/shop/shop.js
import {
  hospitalList,
  doctorList,
  sucessCaseList,
  getCateProducts,
  getProductCate,
  activeCategory,
  categoryByLevel,
  httpGetStr
} from '../../api/apis.js'
const tab1 = 'product'
const tab2 = 'hospital'
const tab3 = 'doctor'
const tab4 = 'example'
const tab5 = 'project'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    scrollTop: 0,
    categoryBoxShow: false,
    boxSelected: tab5,
    categoryList: [],
    categorys: [],
    productList: [],
    hospitalList: [],
    doctorList: [],
    exampleList: [],
    projectList: [],
    pageIndex: 0,
    categorySearch: 0,
    condition: '',
    hasLocation: false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this._checkClass()
    this._getProject()
    this._getProductsCate()
  },
  onShow() {
    if (!this.data.hasLocation) {
      this._getLocation()
    }
  },
  _getLocation() {
    wx.getLocation({
      success: (res) => {
        let lat = res.latitude
        let lng = res.longitude
        this.setData({
          latitude: lat,
          longitude: lng,
          hasLocation: true
        })
        httpGetStr({
          data: {
            lat: lat,
            lng: lng
          },
          success: res => {
            if (res.state) {
              this.setData({
                locationCity: res.data.city
              })
            }
          }
        })
      },
      fail: (res) => {
        this.setData({
          latitude: 0,
          longitude: 0,
          hasLocation: false
        })
      }
    })
  },
  _checkClass() {
    categoryByLevel({
      data: {
        menuID: 5,
        id: 152,
        level: 2
      },
      success: res => {
        if (res.state) {
          let list = []
          res.data.forEach((item, index) => {
            if (index == 0) {
              list.push({
                text: item.GroupName,
                id: item.GroupID,
                selectTxt: item.Url,
                selected: true
              })
            } else {
              list.push({
                text: item.GroupName,
                id: item.GroupID,
                selectTxt: item.Url,
                selected: false
              })
            }
          })
          this.setData({
            categoryList: list
          })
        }
      }
    })
  },
  onCategoryClick(e) {
    let index = e.currentTarget.dataset.index
    let current = "categoryList[" + index + "].selected"
    this.data.categoryList.map((item, index) => {
      item.selected = false
      return item
    })
    this.setData({
      categoryList: this.data.categoryList,
      [current]: true,
      noData: false,
      categorySearch: 0
    })
    //以上都是分类切换时样式的切换
    wx.showLoading({
      title: '获取中...',
      mask: true
    })
    this.setData({
      boxSelected: e.currentTarget.dataset.item.selectTxt,
      pageIndex: 0
    })
    switch (this.data.boxSelected) {
      case tab1:
        this.data.productList = []
        this._getproducts()
        this._getProductsCate('NewProduct')
        break
      case tab2:
        this.data.hospitalList = []
        this._getHospital()
        break
      case tab3:
        this.data.doctorList = []
        this._getDoctor()
        break
      case tab4:
        this.data.exampleList = []
        this._getSuccess()
        break
      case tab5:
        this.data.projectList = []
        this._getProject()
        this._getProductsCate()
        break
    }
    setTimeout(() => {
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 100
      })
    }, 1000)
  },
  categoryBoxShow() {
    this.setData({
      categoryBoxShow: !this.data.categoryBoxShow
    })
  },
  onItemClick(e) {
    switch (this.data.boxSelected) {
      case tab1:
        wx.navigateTo({
          url: '../goods-detail/goods-detail?did=' + e.detail.item.id,
        })
        break
      case tab2:
        wx.navigateTo({
          url: `../hospital-detail/hospital-detail?mid=${e.detail.item.HosID}`,
        })
        break
      case tab3:
        wx.navigateTo({
          url: `../doctor-detail/doctor-detail?mid=${e.detail.item.mid}`,
        })
        break
      case tab4:
        wx.navigateTo({
          url: `../example-detail/example-detail?did=${e.detail.item.mid}`,
        })
        break
      case tab5:
        wx.navigateTo({
          url: `../project-detail/project-detail?did=${e.detail.item.mid}`,
        })
        break
    }
  },
  _getProductsCate(type) {
    getProductCate({
      data: {
        CateName: type ||'VShopProduct'
      },
      success: res => {
        this.setData({
          categorys: res.data
        })
      }
    })
  },
  _getproducts(condition, id) {
    let kw = condition ? condition : ""
    this.data.pageIndex++
    getCateProducts({
      data: {
        index: this.data.pageIndex,
        size: 20,
        condition: kw,
        id: id
      },
      success: res => {
        wx.hideLoading() 
        if (res.state) {
          if (res.state) {
            this.setData({
              productList: this.data.productList.concat(res.data)
            })
          }
        }
      }
    })
  },
  _getHospital(condition) {
    let kw = condition ? condition : ""
    this.data.pageIndex++
    hospitalList({
      data: {
        isTop: false,
        index: this.data.pageIndex,
        size: 20,
        lat: this.data.latitude,
        lng: this.data.longitude,
        condition: kw
      },
      success: res => {
        wx.hideLoading() 
        if (res.state) {
          if (res.data.length>0) {
            res.data.map((item) => {
              item.Distance = item.Distance > 10000 ? '>10km' : item.Distance > 0 ? (item.Distance / 1000).toFixed(2) + 'km' : ''
              item.tag = item.Tags.split('|')
              return item
            })
            this.setData({
              hospitalList: this.data.hospitalList.concat(res.data)
            })
          } else {
            this.setData({
              noData: true
            })
          }
        }
      }
    })
  },
  _getDoctor(condition) {
    let kw = condition ? condition : ""
    this.data.pageIndex++
    doctorList({
      data: {
        isTop: false,
        HosID: 0,
        index: this.data.pageIndex,
        size: 20,
        condition: kw
      },
      success: res => {
        wx.hideLoading() 
        if (res.state) {
          if (res.data.length>0) {
            res.data.map((item) => {
              item.tag = item.Tags.split('|')
              return item
            })
            this.setData({
              doctorList: this.data.doctorList.concat(res.data)
            })
          } else {
            this.setData({
              noData: true
            })
          }
        }
      }
    })
  },
  _getSuccess(condition) {
    let kw = condition ? condition : ""
    this.data.pageIndex++
    sucessCaseList({
      data: {
        index: this.data.pageIndex,
        size: 50,
        types: 0,
        mid: 0,
        condition: kw
      },
      success: res => {
        wx.hideLoading() 
        if (res.state) {
          if (res.data.list.length > 0) {
            let list = []
            res.data.list.forEach((item) => {
              list.push({
                mid: item.mid,
                beforeImg: item.skulist[0].img,
                afterImg: item.skulist[item.skulist.length - 1].img,
                name: item.PatientName,
                doctor: item.DocName,
                bSaying: item.skulist[0].Describe,
                aSaying: item.skulist[item.skulist.length - 1].Describe,
                surgery: item.Operation.split('，')
              })
            })
            this.setData({
              exampleList: this.data.exampleList.concat(list)
            })
          } else {
            this.setData({
              noData: true
            })
          }
          
        }
      }
    })
  },
  _getProject(condition, id) {
    let kw = condition ? condition : ""
    this.data.pageIndex++
    activeCategory({
      data: {
        condition: this.data.condition,
        index: this.data.pageIndex,
        size: 20,
        category: this.data.categorySearch
      },
      success: res => {
        wx.hideLoading() 
        if (res.state) {
          let list = []
          if (res.data.list.length>0) {
            res.data.list.forEach((item) => {
              list.push({
                img: item.FirstImg,
                name: item.title,
                supply: item.yiyuan,
                price: item.sku.length > 0 ? '￥'+item.sku[0].firstPay: '暂无价格',
                sales: item.sales,
                mid: item.IptId,
                SpecialOff: item.SpecialOff
              })
            })
          } else {
            this.setData({
              noData: true
            })
          }
          this.setData({
            projectList: this.data.projectList.concat(list)
          })
        }
      }
    })
  },
  setSearchWords(e) {
    this.setData({
      condition: e.detail.value
    })
  },
  search() {
    switch (this.data.boxSelected) {
      case tab1:
        this.data.productList = []
        this.data.pageIndex = 0
        this._getproducts(this.data.condition)
        break
      case tab2:
        this.data.hospitalList = []
        this.data.pageIndex = 0
        this._getHospital(this.data.condition)
        break
      case tab3:
        this.data.doctorList = []
        this.data.pageIndex = 0
        this._getDoctor(this.data.condition)
        break
      case tab4:
        this.data.exampleList = []
        this.data.pageIndex = 0
        this._getSuccess(this.data.condition)
        break
      case tab5:
        this.data.projectList = []
        this.data.pageIndex = 0
        this._getProject(this.data.condition)
        break
    }
  },
  getBycategory(e) {
    let category = ''
    if (e.currentTarget.dataset.item) {
      category = e.currentTarget.dataset.item.id
    } else {
      category = 0
    }
    this.setData({
      categorySearch: category
    })
    this.data.pageIndex = 0
    switch (this.data.boxSelected) {
      case tab1:
        this.data.productList = []
        this._getproducts("", category)
        break
      case tab5:
        this.data.projectList = []
        this._getProject("", category)
        break
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 500)
  },
  onReachBottom: function() {
    switch (this.data.boxSelected) {
      case tab1:
        this._getproducts()
        break
      case tab2:
        this._getHospital()
        break
      case tab3:
        this._getDoctor()
        break
      case tab4:
        this._getSuccess()
        break
      case tab5:
        this._getProject()
        break
    }
  },
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop
    })
  },
  getMoreConsult() {
    this.setData({
      consultActive: !this.data.consultActive
    })
  },
  callPhone() {
    wx.makePhoneCall({
      phoneNumber: '400-878-6606' //仅为示例，并非真实的电话号码
    })
  }
})